package com.cloud.cloudshop.provider;

import com.alibaba.fastjson.JSON;
import com.cloud.cloudshop.shop.dao.OrderMessageDao;
import com.cloud.common.constant.RabbitmqOrderConstants;
import com.cloud.common.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 54485
 */
@Component
@Slf4j
public class RabbitOrderSender {

    /**
     * 自动注入RabbitTemplate模板类
     */
    private final RabbitTemplate rabbitTemplate;

    private final OrderMessageDao orderMessageDao;


    public RabbitOrderSender(RabbitTemplate rabbitTemplate, OrderMessageDao orderMessageDao) {
        this.rabbitTemplate = rabbitTemplate;
        this.orderMessageDao = orderMessageDao;
    }

    /**
     * 发送消息方法调用: 构建自定义对象消息
     */
    public void sendOrderByDirectExchange(OrderEntity order) throws Exception {
        //消息唯一ID
        CorrelationData correlationData = new CorrelationData(order.getMessageId());
        rabbitTemplate.convertAndSend(RabbitmqOrderConstants.ORDER_DIRECT_EXCHANGE, RabbitmqOrderConstants.ORDER_DIRECT_ROUTING, JSON.parseObject(JSON.toJSONString(order)),m->{
            m.getMessageProperties().setMessageId(order.getMessageId());
//            m.getMessageProperties().setExpiration("3000");  //3秒自动过期。
            m.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            return m;
        }, correlationData);
    }

    public void sendOrderByTopicExchange(OrderEntity order) {
        //消息唯一ID
        CorrelationData correlationData = new CorrelationData(order.getMessageId());
        rabbitTemplate.convertAndSend(RabbitmqOrderConstants.ORDER_TOPIC_EXCHANGE, "topic.test", JSON.parseObject(JSON.toJSONString(order)),m -> {
            m.getMessageProperties().setMessageId(order.getMessageId());
            m.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            return m;
        }, correlationData);


    }

    public void sendOrderByFanoutExchange(OrderEntity order) {
        //消息唯一ID
        CorrelationData correlationData = new CorrelationData(order.getMessageId());
        rabbitTemplate.convertAndSend(RabbitmqOrderConstants.ORDER_FANOUT_EXCHANGE, null, JSON.parseObject(JSON.toJSONString(order)),m -> {
            m.getMessageProperties().setMessageId(order.getMessageId());
            m.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            return m;
        }, correlationData);
    }
}
